#include "color_based_object_tracking.h"

Color_Based_Object_Tracking::Color_Based_Object_Tracking(QWidget *parent)
    : CommonGraphicsView{parent}
{
    this->setWindowTitle("基于颜色的对象跟踪");
    QPushButton *btn = new QPushButton(this);
    btn->setText("选择视频");

    connect(btn,&QPushButton::clicked,[=](){
        openVideoPath();
    });
}

void Color_Based_Object_Tracking::openVideoPath(){
    path = QFileDialog::getOpenFileName(this, tr("选择视频"), ".", tr("video Files(*.mp4 *.avi)"));
    qDebug()<<"视频路径:"<<path;
    showColorObjectTracking(path.toStdString().c_str());
}

void Color_Based_Object_Tracking::showColorObjectTracking(const char* filePath){
    VideoCapture capture;
    capture.open(filePath);
    if(!capture.isOpened()){
        qDebug()<<"无法打开视频";
        return;
    }
    Mat frame,hsv;
    Mat colorMask;
    Mat kernel = getStructuringElement(MORPH_RECT,Size(5,5),Point(-1,-1));
    while(capture.read(frame)){
        cvtColor(frame,hsv,COLOR_BGR2HSV);
        inRange(hsv,Scalar(11, 43, 46),Scalar(25, 255, 255),colorMask);
        //使用形态学开操作消除白点
        morphologyEx(colorMask,colorMask,MORPH_OPEN,kernel,Point(-1,-1),1);
        //使用形态学膨胀操作填充白色区间
        dilate(colorMask,colorMask,kernel,Point(-1,-1),1);

        //轮廓发现
        vector<vector<Point>> contours;
        vector<Vec4i> hir;
        Rect roi;
        findContours(colorMask,contours,RETR_EXTERNAL,CHAIN_APPROX_SIMPLE);
        if(contours.size()>0){
            //过滤轮廓
            double maxArea = 0.0;
            for(size_t i = 0;i<contours.size();i++){
                double area = contourArea(contours[i]);
                if(area>maxArea){
                    maxArea = area;
                    roi = boundingRect(contours[i]);
                }
            }

        }
        //在原图上绘制轮廓
        rectangle(frame,roi,Scalar(0,0,255),3,LINE_8);
        imshow("frame",frame);
        imshow("colorMask",colorMask);
        int key = waitKey(100);
        qDebug()<<"key:"<<key;
        if(key==27){//ese键
            break;
        }
    }
    capture.release();
}
